<?php
namespace app\api\controller\v1;
use app\api\controller\Base;
use app\api\validate\NewAddr;
use app\api\service\Token;
use app\lib\exception\PremEx;
use app\api\model\User;
use app\lib\exception\UserEx;
use app\api\model\UserAddress;

/** 
* Document
*/
class Address extends Base {

    /* 定义前置方法 */
    protected $beforeActionList = [
        'premGtUser' => ['only','createorupdate']
    ];

    

    public function createOrUpdate(){
        # 1.参数校验
        $valid = new NewAddr();
        $valid->goCheck();
        $data = $valid->passData();
        // token校验，从token中换取uid
        $token = Token::getFromHttp();
        // if(! $token) throw new PremEx('未携带Token',40003);
        $uid = Token::getCacheValue($token,'uid');
        if(! $uid) throw new PremEx('登录超时',40001);
        // 用户信息校验
        $user = User::get($uid);
        if (! $user) throw new UserEx('用户不存在',50001);
        // 新增或更新用户收货地址
        $userAddr = $user->address;
        if(! $userAddr){
            $data['user_id'] = $uid;
            $userAddr = new UserAddress($data);
            $res = $userAddr->save();
        }else{
            $res = $userAddr->save($data);
        }
        # 操作结果校验，返回客户端
        if($res === false) return $this->data([],'操作失败',500,1);
        else               return $this->data([],'操作成功',201);
    }
}